<template>
  <el-drawer v-model="dialogVisible"  title="上传文件" size="90%">
    <div v-if="selectedFileDetails.length" style="margin-bottom: 16px;text-align: center;">
      <el-tag v-for="file in selectedFileDetails" :key="file.id" closable @close="removeFile(file.id)"
        style="margin-right: 8px;">
        {{ file.title }}
      </el-tag>
    </div>
    <FileSelect :folderDisabled="folderDisabled" v-model="checkedFiles" />
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="cancelForm">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import FileSelect from './fileSelect.vue'
import { computed, ref, watch } from 'vue'
import * as FileApi from '@/api/infra/file'

// mock FileApi.getFileListByIds
const getFileListByIds = async (ids: string[]) => {
  // 实际项目应调用后端接口，这里 mock 返回
  return FileApi.getFileListByIds(ids)
}

defineOptions({ name: 'FileDialog' })

const props = defineProps<{
  modelValue: string[],
  folderDisabled?: Boolean, // 是否禁用文件夹选择
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
  (e: 'success', value: string[]): void
  (e: 'cancel', value: string[]): void
}>()

const checkedFiles = computed({
  get: () => props.modelValue,
  set: (val: string[]) => emit('update:modelValue', val)
})

const selectedFileDetails = ref<{ id: string, title: string }[]>([])

watch(checkedFiles, async (newVal) => {
  if (!newVal || newVal.length === 0) {
    selectedFileDetails.value = []
    return
  }
  selectedFileDetails.value = await getFileListByIds(newVal)
}, { immediate: true })

const removeFile = (id: string) => {
  emit('update:modelValue', checkedFiles.value.filter(fid => fid !== id))
}

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // formData.value = await AttendanceDetailApi.getAttendanceDetail(id)
    } finally {
      formLoading.value = false
    }
  }
} 
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  emit('success', checkedFiles.value)
  dialogVisible.value = false
}
const cancelForm = () => {
  dialogVisible.value = false
  // emit('cancel', [])
  // emit('update:modelValue', [])
}
</script>